package com.xiaoran.user20012.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoran.commonapi.tencent.Sms;
import com.xiaoran.commonapi.utils.StringUtils;
import com.xiaoran.user20012.entity.XrUser;
import com.xiaoran.user20012.mapper.XrUserMapper;
import com.xiaoran.user20012.service.IXrUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xiaoRan
 * @since 2022-03-10
 */
@Service
@Slf4j
public class XrUserServiceImpl extends ServiceImpl<XrUserMapper, XrUser> implements IXrUserService {
    @Autowired
    XrUserMapper mapper;
    @Autowired
    Sms sms;

    @Override
    public XrUser login(String phone, Integer code) {
        // 验证验证码
        if (!sms.verifyCode(phone, code.toString())) {
            return null;
        }
        // 判断数据库是否已有该用户
        XrUser user = getUser(phone);
        if (user == null) {
            // 不存在用户，首次登录生成信息
            user = new XrUser();
            // 用户账号12位 xxxx-xx-xx-四位随机字母
            StringBuilder userId = new StringBuilder();
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH);
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            String s = StringUtils.random_str(4);
            String userid = userId.append(year).append(month).append(day).append(s).toString();
            user.setUserId(userid);
            if (!saveUser(user)) {
                log.error("用户信息保存失败");
                user = null;
            }
        }
        return user;
    }

    @Override
    public XrUser getUser(String phone) {
        return mapper.selectOne(new QueryWrapper<XrUser>().eq("phone", phone));
    }

    @Override
    public boolean saveUser(XrUser xrUser) {
        return mapper.insert(xrUser) == 1;
    }
}
